package com.yzc.android.network.base;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.yzc.android.common.utils.DeviceUtils;
import com.yzc.android.event.NetworkStateEvent;
import com.yzc.android.KDApp;
import okhttp3.OkHttpClient;

/**
 * Created by yzc on 16/1/29.
 */
public class KDRequestQueue {
    private RequestQueue mRequestQueue;

    public RequestQueue getRequestQueue()
    {
        return mRequestQueue;
    }

    public KDRequestQueue(Context context) {
        mRequestQueue = Volley3.newRequestQueue(context, new OkHttp3Stack(new OkHttpClient()));
    }

    public <T> Request<T> add(Request<T> request, final Response.ErrorListener errorListener)
    {
        if (!DeviceUtils.isNetworkAvailable(KDApp.getInstance()))
        {
            KDApp.getInstance().getEventBus().post(new NetworkStateEvent(BaseErrorCode.APP_BAD_NETWORK));
            if (errorListener != null)
            {
                KDVolleyError error = new KDVolleyError(BaseErrorCode.APP_BAD_NETWORK, "");
                errorListener.onErrorResponse(error);
            }
            return null;
        }
        // 请求参数错误，用error的方式回调，便于统一处理界面逻辑
        if (request == null && errorListener != null)
        {
            KDVolleyError error = new KDVolleyError(BaseErrorCode.APP_BAD_REQUEST_PARAMS, "");
            errorListener.onErrorResponse(error);
            return null;
        }
        return mRequestQueue.add(request);
    }
}
